<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
      <!-- 添加角色 -->
      <el-button type="primary" @click="openDialogRoles">添加角色</el-button>
      <!-- 角色列表区域 -->
      <el-table :data="rolesList" border stripe>
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
              v-for="(item, index) in scope.row.children"
              :key="item.id"
              :class="['bdButtom', index === 0 ? 'bdTop' : '', 'valign']"
            >
              <!-- 渲染一级权限 -->
              <el-col :span="5"
                ><el-tag>{{ item.authName }}</el-tag
                ><i class="el-icon-caret-right"></i
              ></el-col>
              <!-- 渲染二级和三级权限 -->
              <el-col :span="19">
                <!-- 通过for循环渲染二级菜单 -->
                <el-row
                  v-for="(item1, index1) in item.children"
                  :key="item1.id"
                  :class="[index1 === 0 ? '' : 'bdTop', 'valign']"
                >
                  <el-col :span="6"
                    ><el-tag type="success">{{ item1.authName }}</el-tag
                    ><i class="el-icon-caret-right"></i
                  ></el-col>
                  <!-- 渲染三级权限 -->
                  <el-col :span="18">
                    <el-tag
                      @close="removeRights(scope.row, item2.id)"
                      closable
                      type="warning"
                      v-for="item2 in item1.children"
                      :key="item2.id"
                      >{{ item2.authName }}</el-tag
                    >
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <!-- 索引列 -->
        <el-table-column type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <!-- 编辑 -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="openEditDialog(scope.row.id)"
              >编辑</el-button
            >
            <!-- 删除 -->
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="deleteUserById(scope.row.id)"
              >删除</el-button
            >
            <!-- 分配权限 -->
            <el-button
              type="warning"
              size="mini"
              icon="el-icon-setting"
              @click="showRightDialog(scope.row)"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 添加用户对话框区域 -->
    <el-dialog
      title="添加角色"
      :visible.sync="addRoleDialog"
      width="50%"
      @close="resetsForm"
    >
      <!-- 正文 -->
      <el-form
        ref="addRoleFormRef"
        :model="addRoleForm"
        label-width="80px"
        :rules="addRoleFormRules"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addRoleForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addRoleForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部模块区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addRoleDialog = false">取 消</el-button>
        <el-button type="primary" @click="addRoles">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑角色对话框 -->
    <el-dialog
      title="修改用户"
      :visible.sync="showRoleDialogVisible"
      width="50%"
      @close="editRoleDialogClose"
    >
      <!-- 主体内容 -->
      <el-form
        ref="editRoleFormRef"
        :model="editRoleForm"
        label-width="80px"
        :rules="addRoleFormRules"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editRoleForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editRoleForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="showRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editRoles">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配权限对话框 -->
    <el-dialog
      title="分配权限"
      :visible.sync="rightDialogVisible"
      width="50%"
      @close="shutDialog"
    >
    <!-- 主体 -->
    <el-tree ref="treeEntity" :data="rightList" :props="treeProp" show-checkbox node-key="id" default-expand-all :default-checked-keys="defArry"></el-tree>

      <span slot="footer" class="dialog-footer">
        <el-button @click="rightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allowRights"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'Roles',
  created() {
    this.getRoleList()
  },
  data() {
    return {
      //获取所有角色列表
      rolesList: [],
      //对话框关闭
      addRoleDialog: false,
      //编辑角色对话框关闭
      showRoleDialogVisible: false,
      //添加用户的表单数据
      addRoleForm: {
        roleName: '',
        roleDesc: '',
      },
      // 添加表单规则
      addRoleFormRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' },
        ],
      },
      //获取角色信息
      editRoleForm: {},
      //展示权限对话框
      rightDialogVisible:false,
      //获取所有权限数据
      rightList:[],
      //树形控件的属性绑定对象
      treeProp:{
          label:'authName',
          children:'children'
      },
      defArry:[],
      //得到分配权限的id
      getRightId: ''
    }
  },
  methods: {
    //获取角色列表
    async getRoleList() {
      const { data: res } = await this.$https.get('roles')
      if (res.meta.status != 200) {
        return this.$message.error('请求角色列表失败！ ')
      }
      this.rolesList = res.data
      console.log(res.data)
    },
    //添加角色,打开对话框
    openDialogRoles() {
      this.addRoleDialog = true
    },
    // 重置添加角色时的表单数据
    resetsForm() {
      this.$refs.addRoleFormRef.resetFields()
    },
    //添加角色
    addRoles() {
      //表单预验证
      this.$refs.addRoleFormRef.validate(async (valid) => {
        if (!valid) return
        //可以发起添加角色请求
        const { data: res } = await this.$https.post('roles', this.addRoleForm)
        console.log(res)
        if (res.meta.status != 201) {
          return this.$message.error('添加角色失败！')
        }
        this.$message.success('添加角色成功！')
        //关闭用户添加角色对话框
        this.addRoleDialog = false
        //刷新页面
        this.getRoleList()
      })
    },
    //打开修改角色对话框，并根据id查询角色
    async openEditDialog(id) {
      this.showRoleDialogVisible = true
      const { data: res } = await this.$https.get('roles/' + id)
      if (res.meta.status != 200) {
        return this.$message.error('查询角色信息失败！')
      }
      this.$message.success('查询角色信息成功！')
      this.editRoleForm = res.data
    },
    //重置修改角色对话框
    editRoleDialogClose() {
      this.$refs.editRoleFormRef.resetFields()
    },
    // 修改角色信息
    async editRoles() {
      //表单预验证
      this.$refs.editRoleFormRef.validate(async (valid) => {
        if (!valid) return
        //可以发起编辑角色请求
        const { data: res } = await this.$https.put(
          'roles/' + this.editRoleForm.roleId,
          {
            roleName: this.editRoleForm.roleName,
            roleDesc: this.editRoleForm.roleDesc,
          }
        )
        if (res.meta.status != 200) {
          return this.$message.error('编辑角色失败！')
        }
        this.$message.success('编辑角色成功！')
        //关闭用户编辑角色对话框
        this.showRoleDialogVisible = false
        //刷新页面
        this.getRoleList()
      })
    },
    //通过id删除角色
    async deleteUserById(id) {
      const resResult = await this.$confirm(
        '此操作将永久删除该用户, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch((error) => error)
      if (resResult !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      const { data: res } = await this.$https.delete('roles/' + id)
      if (res.meta.status != 200) {
        return this.$message.error('删除失败！')
      }
      this.$message.success('删除成功！')
      this.getRoleList()
    },
    //根据id删除对应的权限
    async removeRights(role, rightId) {
      const resResult = await this.$confirm(
        '此操作将永久删除该用户, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch((error) => error)
      if (resResult !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      const { data: res } = await this.$https.delete(
        `roles/${role.id}/rights/${rightId}`
      )
      if (res.meta.status != 200) {
        return this.$message.error('删除失败！')
      }
      this.$message.success('删除成功！')
      role.children = res.data
    },
    //展示分配权限对话框
   async showRightDialog(node) {
        this.rightDialogVisible =true
        //获取所有权限的数据
        this.rightId = node.id
        const {data:res} = await this.$https.get('rights/tree')
        if (res.meta.status != 200) {
        return this.$message.error('获取所有权限失败！')
      }
      this.$message.success('获取所有权限成功！')
      this.rightList = res.data
      // 递归获取三级节点的id
      this.getLeafKeys(node,this.defArry)
      console.log(this.rightList)
    },
    //定义分配权限的方法
    getLeafKeys(node,arry) {
      //如果当前节点没有children属性说明是三级节点
      if (!node.children) {
        return arry.push(node.id)
      }
      node.children.forEach(item=>this.getLeafKeys(item,arry))
    },
    //关闭分配权限对话框，清空数组id值
    shutDialog() {
      this.defArry = []
    },
    //分配权限
    async allowRights() {
      const arry = [...this.$refs.treeEntity.getCheckedKeys(),...this.$refs.treeEntity.getHalfCheckedKeys()]
      const arryKeys = arry.join(',')
      const {data:res} = await this.$https.post(`roles/${this.rightId}/rights`,{
        rids:arryKeys
      })
      if (res.meta.status != 200) {
        this.$message.error('分配权限失败！')
      }
      this.$message.success('分配权限成功！')
      this.rightDialogVisible =false
      this.getRoleList()
    }
  },
}
</script>

<style lang="less" scoped>
.bdTop {
  border-top: 1px solid #eee;
}
.bdButtom {
  border-bottom: 1px solid #eee;
}
.el-tag {
  margin: 7px;
}
.valign {
  display: flex;
  align-items: center;
}
</style>